package com.furnitur.modules.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.core.entity.cart.Cart;
import com.furnitur.core.entity.product.Furniture;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.cart.CartMapper;
import com.furnitur.core.mapper.product.FurnitureMapper;
import com.furnitur.modules.portal.dto.cart.CartAddDTO;
import com.furnitur.modules.portal.service.PortalCartService;
import com.furnitur.modules.portal.vo.cart.CartVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class PortalCartServiceImpl implements PortalCartService {

    @Autowired
    private CartMapper cartMapper;
    
    @Autowired
    private FurnitureMapper furnitureMapper;

    @Override
    @Transactional
    public void addToCart(CartAddDTO dto) {
        // 获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 查询商品信息
        Furniture furniture = furnitureMapper.selectById(dto.getFurnitureId());
        if (furniture == null) {
            throw new RuntimeException("商品不存在");
        }

        // 检查商品状态
        if (furniture.getStatus() != 1) {
            throw new RuntimeException("商品已下架");
        }

        // 检查库存
        if (furniture.getStock() < dto.getQuantity()) {
            throw new RuntimeException("商品库存不足");
        }

        // 检查购物车是否已存在该商品
        Cart existCart = cartMapper.selectOne(new QueryWrapper<Cart>()
                .eq("user_id", currentUser.getId())
                .eq("furniture_id", dto.getFurnitureId()));

        if (existCart != null) {
            // 更新数量
            int newQuantity = existCart.getQuantity() + dto.getQuantity();
            if (newQuantity > furniture.getStock()) {
                throw new RuntimeException("商品库存不足");
            }
            existCart.setQuantity(newQuantity);
            cartMapper.updateById(existCart);
        } else {
            // 新增购物车记录
            Cart cart = new Cart();
            cart.setUserId(currentUser.getId());
            cart.setFurnitureId(dto.getFurnitureId());
            cart.setQuantity(dto.getQuantity());
            cartMapper.insert(cart);
        }
    }

    @Override
    public List<CartVO> getCartList() {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }
        return cartMapper.selectUserCartItems(currentUser.getId());
    }

    @Override
    @Transactional
    public void updateQuantity(Long cartId, Integer quantity) {
        // 验证购物车记录
        Cart cart = validateCartOwnership(cartId);
        
        // 验证库存
        Furniture furniture = furnitureMapper.selectById(cart.getFurnitureId());
        if (furniture == null || furniture.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        // 更新数量
        cart.setQuantity(quantity);
        cartMapper.updateById(cart);
    }

    @Override
    public void deleteCartItem(Long cartId) {
        Cart cart = validateCartOwnership(cartId);
        cartMapper.deleteById(cart.getId());
    }

    private Cart validateCartOwnership(Long cartId) {
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        Cart cart = cartMapper.selectById(cartId);
        if (cart == null || !cart.getUserId().equals(currentUser.getId())) {
            throw new RuntimeException("购物车记录不存在");
        }

        return cart;
    }
} 